package com.pengtu.gsj.service.impl.check.gcjs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.dao.base.QueryFilter.MatchType;
import com.pengtu.gsj.dao.check.gcjs.XXRoadConstructionADao;
import com.pengtu.gsj.dao.check.gcjs.XXRoadConstructionBDao;
import com.pengtu.gsj.dao.system.AttachmentDao;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.entity.gcjs.XXRoadConstructionA;
import com.pengtu.gsj.entity.gcjs.XXRoadConstructionB;
import com.pengtu.gsj.service.check.CheckTableService;
import com.pengtu.gsj.service.check.gcjs.CouRoadConService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.utils.DateUtils;
import com.pengtu.gsj.utils.MathsUtils;

@Service
@Transactional
public class CouRoadConServiceImpl implements CouRoadConService{

	@Autowired
	private AttachmentDao attachmentDao;
	@Autowired
	private CheckTableService checkTableService;
	@Autowired
	private SystemManageService systemManageService;
	@Autowired
	private XXRoadConstructionBDao xxRoadConstructionBDao;
	@Autowired
	private XXRoadConstructionADao xxRoadConstructionADao;

	@Override
	public List<XXRoadConstructionB> getxxRoadConstructionB(QueryFilter queryFilter) {
		return xxRoadConstructionBDao.find(queryFilter);
	}

	@Override
	public List<XXRoadConstructionB> getxxRoadConstructionB() {
		return xxRoadConstructionBDao.find();
	}

	@Override
	public List<XXRoadConstructionA> getXXRoadConstructionA(QueryFilter queryFilter) {
		return xxRoadConstructionADao.find(queryFilter);
	}
	
	@Override
	public Map<String, Object> getCouRoadCons(String startTime, String endTime, CheckTable checkTable, String tag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Object> values = new ArrayList<Object>();
		List<Attachment> list = new ArrayList<Attachment>();
		List<XXRoadConstructionB> xxRoadBLists = new ArrayList<XXRoadConstructionB>();
		List<XXRoadConstructionA> xxRoadConstructionAs = new ArrayList<XXRoadConstructionA>();
		
		// 获取前端条件数据
		JSONObject jsonObject = JSONObject.parseObject(checkTable.getRetrieval());
		//检查表二获取项目id
		String proId = (String) jsonObject.get("itemProjectId");
		// 基建程序得分
		double infraAll = Double.parseDouble((String) jsonObject.get("yearPart"));
		// 每个部、省补助县乡公路满分
		double poitMark = Double.parseDouble((String) jsonObject.get("poitMark"));
		// 项目100%开工可得
		double allOpen = Double.parseDouble((String) jsonObject.get("reserveMark"));
		// 项目90%及以上完工可得
		double allComp = Double.parseDouble((String) jsonObject.get("firstStepScore"));
		// 项目90%及以上验收可得
		double allAccep = Double.parseDouble((String) jsonObject.get("secondStepScore"));
		// 开工率每降低1个百分点扣分
		double workScore = Double.parseDouble((String) jsonObject.get("thirdStepScore"));
		// 完工率每降低1个百分点扣分
		double compScore = Double.parseDouble((String) jsonObject.get("fourthStepScore"));
		// 验收率每降低1个百分点扣分
		double accepScore = Double.parseDouble((String) jsonObject.get("fifthStepScore"));
		double total = 0; 							    // 检查总分
		double tableFull = 0; 							 // 表总分
		double totalOne = 0;						 // 表一检查得分
		double totalTwo = 0;						 // 表二检查得分
		double percentage = 0; 						  // 系统完善度
		double workNum = 0; 							//开工比例
		double completeNum = 0; 						//完工比例
		double acceptNum = 0; 							//验收比例
		double comAndAccepFull = MathsUtils.sum(allOpen, allComp, allAccep);  // 全部完成且验收及时满分
		
		// 根据时间、标签查询是否有附件
		list = systemManageService.getAllCheckAttachments(startTime, endTime, tag);
		//1、检查表一的算分
		//自定义查询所有的工程总数、开工率、完工率和验收率
		xxRoadConstructionAs = xxRoadConstructionADao.searchForResult(startTime, endTime);
		XXRoadConstructionA xxRoadConA = xxRoadConstructionAs.get(0);
		if (null != xxRoadConA.getWorkNum()){
			// 获开工率、完工率和验收率
			workNum = xxRoadConA.getWorkNum();
			completeNum = xxRoadConA.getCompleteNum();
			acceptNum = xxRoadConA.getAcceptNum();
			// 根据项目平均的开工率、完工率和验收率计算检查得分
			if (workNum >= 100 && completeNum >= 90 && acceptNum >= 90) {
				totalOne = comAndAccepFull;
			} else {
				if (workNum >= 100) {
					totalOne = allOpen;
				} else {
					totalOne = allOpen - (100 - workNum) * workScore;
				}
				if (completeNum >= 90) {
					totalOne += allComp;
				} else {
					totalOne += (allComp - (90 - completeNum) * compScore);
				}
				if (acceptNum >= 90) {
					totalOne += allAccep;
				} else {
					totalOne += (allAccep - (90 - acceptNum) * accepScore);
				}
				// 设置一个临时变量保存分数
				double tempScore = 0;
				// 检查对应的附件是否有文件，有的加分，没有的不加分
				tempScore += systemManageService.getCheckAttachmentByTag(startTime, endTime, "xxgl_xmwj").size() > 0 ? infraAll / 4 : 0;
				tempScore += systemManageService.getCheckAttachmentByTag(startTime, endTime, "xxgl_sjwj").size() > 0 ? infraAll / 4 : 0;
				tempScore += systemManageService.getCheckAttachmentByTag(startTime, endTime, "xxgl_ztbb").size() > 0 ? infraAll / 4 : 0;
				tempScore += systemManageService.getCheckAttachmentByTag(startTime, endTime, "xxgl_yssx").size() > 0 ? infraAll / 4 : 0;
				// 将计算的分数返回
				if (Math.abs(tempScore - infraAll) == 0) {
					map.put("ifPerfect", true);
				}
				totalOne = MathsUtils.formatDoubleUp(totalOne + tempScore, 2);
				// 添加一个标记，确定前端是否输出表格
				map.put("flagOne", true);
				values.add("true");
			}	
		}
		
		//2、检查表二的算分
		if (StringUtils.isNotEmpty(proId)) {
			//通过逗号将每个id切割出来，并搜索算分
			String[] idArrs = proId.split(",");
			for (int i = 0; i < idArrs.length; i++) {
				//根据tag检索是否有附件
				if( i > 1) {
					break;
				}
				XXRoadConstructionB xxRoadB = xxRoadConstructionBDao.get(idArrs[i]);
				xxRoadBLists.add(xxRoadB);
			}
			totalTwo = poitMark;
			map.put("flagTwo", true);
			map.put("xxRoadBLists", xxRoadBLists);
			map.put("scoreTwo", totalTwo);
		}
		// 计算总得分
		total = MathsUtils.formatDoubleUp(totalOne + totalTwo, 2);
		// 计算完善度
		tableFull = MathsUtils.sum(comAndAccepFull, infraAll, totalTwo);
		percentage = MathsUtils.divDouble(total * 100, tableFull, 2);

		// 只有当系统完善度和检查得分不相等的情况下才更新数据 避免每次搜索都更新数据
		checkTableService.updateCheckTable(checkTable, percentage, total, tableFull, values);
		completeNum = MathsUtils.formatDoubleUp(completeNum, 2);
		map.put("checkTime", startTime + "~" + endTime);
		map.put("itemSum", xxRoadConA.getItemNum());
		map.put("workNum", workNum);
		map.put("completeNum", completeNum);
		map.put("acceptNum", acceptNum);
		map.put("scoreOne", totalOne);
		map.put("score", total);
		map.put("percent", percentage);
		map.put("att", list);
		map.put("checkTable", checkTable);
		return map;
	}

	//根据tag查询是否存在对应附件
	@Override
	public List<Attachment> getAttByTag(String tagName) {
		return attachmentDao.findBy("tag", tagName);
	}

	@Override
	public List<XXRoadConstructionB> getCouRoadConPro(QueryFilter queryFilter) {
		return xxRoadConstructionBDao.find(queryFilter, "year", true);
	}
	
	/**
	 * 将检索条件封装
	 */
	@Override
	public List<XXRoadConstructionA> getCheckData(String startTime, String endTime, String year) {
		QueryFilter queryFilter = new QueryFilter();
		if (StringUtils.isNotEmpty(startTime) && DateUtils.isDate(startTime)) {
			queryFilter.addFilter("year", startTime, MatchType.GE);
		}
		if (StringUtils.isNotEmpty(endTime) && DateUtils.isDate(endTime)) {
			queryFilter.addFilter("year",  endTime, MatchType.LE);
		}
		if (StringUtils.isNotEmpty(year)) {
			queryFilter.addFilter("year", year, MatchType.EQ);
		}
		return xxRoadConstructionADao.find(queryFilter);
	}
}
